/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package exatrez.stripes.action;

import able.stripes.JSP;
import com.google.inject.Inject;
import exatrez.dao.DepartmentDAO;
import exatrez.dao.GroupDAO;
import exatrez.dao.PenggunaDAO;
import exatrez.dao.UserGroupDAO;
import exatrez.manager.UserManager;
import exatrez.model.Department;
import exatrez.model.Groups;
import exatrez.model.InfoAudit;
import exatrez.model.User;
import exatrez.model.UserGroup;
import exatrez.stripes.ActiveDActionBean;
import exatrez.stripes.BaseActionBean;
import exatrez.stripes.config.AuthRequired;
import exatrez.stripes.util.EncyptUtil;
import java.util.Date;
import java.util.List;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.UrlBinding;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author wan.fairul
 */
@UrlBinding("/adminUser")
@AuthRequired
public class UserAction extends BaseActionBean {

    private static Logger LOG = LoggerFactory.getLogger(UserAction.class);
    private User staff;
    private String roles;
    private String department;
    @Inject
    private UserManager usermanager;
    @Inject
    private EncyptUtil encyptUtil;
    private List<User> listOfStaff;
    @Inject
    private PenggunaDAO penggunaDAO;
    @Inject
    private UserGroupDAO userGroupDAO;
    @Inject
    private GroupDAO groupDAO;
    @Inject
    private DepartmentDAO departmentDAO;

    @DefaultHandler
    public Resolution add_user() {
        staff = new User();
        listOfStaff = usermanager.findAll();
        return new JSP("admin/user.jsp");
    }

    public Resolution savePengguna() {
        User user = getContext().getCurrentUser();
        User u = penggunaDAO.findById(staff.getUserId());
        if (u == null) {
            String encrypted = encyptUtil.encrypt(staff.getPassword());
            InfoAudit ia = new InfoAudit();
            ia.setCreateDate(new Date());
            ia.setCreateId(user);
            staff.setUserId(staff.getUserId().toLowerCase());
            staff.setEmail(staff.getEmail() + "@iconoffshore.com.my");
            staff.setInfoAudit(ia);
            staff.setPassword(encrypted);
//            if(staff.getAdName() != null)
//            {
//                 ActiveDActionBean activeD = new ActiveDActionBean();
//                if(activeD.authenticateAD(encrypted, encrypted)){
//            }
            staff.setActivate('Y');
            LOG.debug(department);
            Department d = departmentDAO.findById(Integer.parseInt(department));
            staff.setDepartment(d);
            usermanager.saveOrUpdateUser(staff);
            //For User Group
            Groups g = groupDAO.findById(Integer.parseInt(roles));
            if (roles != null) {
                UserGroup usergroup = new UserGroup();
                usergroup.setUser(staff);
                usergroup.setActive('Y');
                usergroup.setGroup(g);
                usergroup.setInfoAudit(ia);
                usergroup.setObsFlag("F");
                usermanager.saveOrUpdateGroup(usergroup);
            }
            addSimpleMessage("Success");
            LOG.debug("finish");
        } else {
            addSimpleError("Duplicate User!");
        }
        return add_user();
    }

    public Resolution deleteStaff() {
        String userId = getContext().getRequest().getParameter("userId");
        if (userId != null) {
            staff = penggunaDAO.findById(userId);
            if (staff != null) {
                UserGroup ug = usermanager.findUserId(staff.getUserId());
                if (ug != null) {
                    usermanager.deleteUserGroup(ug);
                    usermanager.deleteUser(staff);
                    addSimpleMessage("Success Delete");
                }

            }
        }
        return new RedirectResolution(UserAction.class, "add_user");
    }

    public Resolution popupEditUser() {
        String userId = getContext().getRequest().getParameter("userId");
        if (userId != null) {
            staff = penggunaDAO.findById(userId);
        }
        return new JSP("admin/edit_user.jsp").addParameter("popup", "true");
    }

    public Resolution saveEditUser() {
        String userId = getContext().getRequest().getParameter("staff.userId");
        if (userId != null) {
            User u = penggunaDAO.findById(userId);
            User user = getContext().getCurrentUser();
            InfoAudit ia = u.getInfoAudit();
            if (staff.getPassword() != null) {
                String encrypted = encyptUtil.encrypt(staff.getPassword());
                u.setPassword(encrypted);
            }
            ia.setUpdateDate(new Date());
            ia.setUpdateId(user);
            u.setInfoAudit(ia);
            u.setDepartment(staff.getDepartment());
            u.setActivate(staff.getActivate());
            u.setEmail(staff.getEmail());
            u.setScorePoint(staff.getScorePoint());
            u.setAdName(staff.getAdName());
            usermanager.saveOrUpdateUser(u);
            roles = getContext().getRequest().getParameter("roles");
            if (StringUtils.isNotBlank(roles)) {
                for (UserGroup ug : u.getRoles()) {
                    UserGroup p = usermanager.findUserIdGroup(u.getUserId(), String.valueOf(ug.getGroup().getGroupId()));
                    Groups g = groupDAO.findById(Integer.parseInt(roles));
                    p.setUser(u);
                    p.setActive(staff.getActivate());
                    p.setGroup(g);
                    p.setInfoAudit(ia);
                    usermanager.saveOrUpdateGroup(p);
                }
            } else {
                for (UserGroup ug : u.getRoles()) {
                    UserGroup p = usermanager.findUserIdGroup(u.getUserId(), String.valueOf(ug.getGroup().getGroupId()));
                    p.setUser(u);
                    p.setActive(staff.getActivate());
                    p.setInfoAudit(ia);
                    usermanager.saveOrUpdateGroup(p);
                }
            }
            addSimpleMessage("Success");
            LOG.debug("finish");
        }

        return new RedirectResolution(UserAction.class, "add_user");
    }

    public User getStaff() {
        return staff;
    }

    public void setStaff(User staff) {
        this.staff = staff;
    }

    public UserManager getUsermanager() {
        return usermanager;
    }

    public void setUsermanager(UserManager usermanager) {
        this.usermanager = usermanager;
    }

    public EncyptUtil getEncyptUtil() {
        return encyptUtil;
    }

    public void setEncyptUtil(EncyptUtil encyptUtil) {
        this.encyptUtil = encyptUtil;
    }

    public List<User> getListOfStaff() {
        return listOfStaff;
    }

    public void setListOfStaff(List<User> listOfStaff) {
        this.listOfStaff = listOfStaff;
    }

    public PenggunaDAO getPenggunaDAO() {
        return penggunaDAO;
    }

    public void setPenggunaDAO(PenggunaDAO penggunaDAO) {
        this.penggunaDAO = penggunaDAO;
    }

    public UserGroupDAO getUserGroupDAO() {
        return userGroupDAO;
    }

    public void setUserGroupDAO(UserGroupDAO userGroupDAO) {
        this.userGroupDAO = userGroupDAO;
    }

    public String getRoles() {
        return roles;
    }

    public void setRoles(String roles) {
        this.roles = roles;
    }

    public GroupDAO getGroupDAO() {
        return groupDAO;
    }

    public void setGroupDAO(GroupDAO groupDAO) {
        this.groupDAO = groupDAO;
    }

    public DepartmentDAO getDepartmentDAO() {
        return departmentDAO;
    }

    public void setDepartmentDAO(DepartmentDAO departmentDAO) {
        this.departmentDAO = departmentDAO;
    }

    public String getDepartment() {
        return department;
    }

    public void setDepartment(String department) {
        this.department = department;
    }
}
